import React, { useEffect, useState } from 'react';
import { Box, IconType, SimpleAccordion } from '@nova-hf/ui';
import ServiceWrapper from 'beta/containers/layout/ServiceWrapper';
import Authentication from 'beta/store/authentication';
import { IContext } from 'beta/typings/context';
import { isDev, serviceColorMap } from 'beta/utils/helpers';
import { inject } from 'mobx-react';
import { useRouter } from 'next/router';
import {
  ContractStatus,
  FiberProvider,
  useContractsQuery,
  useCustomerIsCompanyQuery,
  useGetTerminationsQuery,
  useServiceQuery,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

import FiberServiceTermination from '../containers/FiberServiceTermination';

import AbroadSettingsContainer from './containers/AbroadSettingsContainer';
import CancelContractContainer from './containers/CancellContractContainer';
import ChangeCeilingContainer from './containers/ChangeCeilingContainer';
import ChangeInvoiceDescription from './containers/ChangeInvoiceDescription';
import ChangeServiceContainer from './containers/ChangeServiceContainer';
import { DepartmentSettingsContainer } from './containers/DepartmentSettingsContainer';
import GeneralSettingsContainer from './containers/GeneralSettingsContainer';
import MoveSettingsContainer from './containers/MoveSettingsContainer';
import PayersettingsContainer from './containers/PayerSettingsContainer';
import PaymentMethod from './containers/PaymentMethod';
import { PhonenumberSettingsContainer } from './containers/PhonenumberSettingsContainer';
import { ServiceSettingsContainer } from './containers/ServiceSettingsContainer';
import SimcardSettingsContainer from './containers/SimcardSettingsContainer';
import { UserInfoSettingsContainer } from './containers/UserInfoSettingsContainer';
import { UserSettingsContainer } from './containers/UserSettingsContainer';

type ThjonustaProp = {
  authentication?: Authentication;
};

type SettingsCategoriesType = {
  id: string;
  name: string;
  icon: IconType;
  content: JSX.Element;
  active: boolean;
};

const Thjonusta = ({ authentication }: ThjonustaProp) => {
  const { t } = useTranslation('stillingar');
  const router = useRouter();
  const serviceId = typeof router?.query?.serviceId === 'string' ? router?.query?.serviceId : '';
  const customerId = typeof router?.query?.customerId === 'string' ? router?.query?.customerId : '';

  const [selectedAccordionIds, setSelectedAccordionIds] = useState<string[]>();

  const { data, loading, error } = useServiceQuery({
    variables: {
      serviceId: (router.query.serviceId as string) ?? '',
    },
  });

  const { data: contractsData } = useContractsQuery({
    variables: {
      input: {
        serviceId,
        customerId,
      },
    },
    skip: !serviceId || !customerId,
  });

  const contract = contractsData?.contracts.contracts.find(
    (contract) =>
      contract.status === ContractStatus.Active || contract.status === ContractStatus.Pending,
  );
  const isAlltSaman = contract?.variant?.productName?.toLowerCase() === 'alltsaman';
  const contractId = contract?.id;

  const { data: isPayerCompanyData } = useCustomerIsCompanyQuery({
    variables: {
      input: { id: contract?.payerId },
    },
  });

  const { data: isCompanyData } = useCustomerIsCompanyQuery({
    variables: {
      input: { id: router?.query?.nationalId?.toString() ?? '' },
    },
  });

  const { data: terminationsData, refetch: terminationRefetch } = useGetTerminationsQuery({
    variables: {
      input: { serviceId },
    },
  });

  const termination = terminationsData?.terminations?.find(
    (termination) => !termination.isProcessed && !termination.isCancelled,
  );
  const hasTermination = !!termination;

  useEffect(() => {
    if (router.query.stilling && typeof router.query.stilling === 'string') {
      const queryStillingString = router.query.stilling;
      const queryStillingToArr: string[] = queryStillingString.split('-');
      setSelectedAccordionIds(queryStillingToArr);
    }
  }, []);

  useEffect(() => {
    if (selectedAccordionIds?.length) {
      const accordionQueryIds = selectedAccordionIds.join('-');
      router.replace(
        {
          query: { ...router.query, stilling: accordionQueryIds },
        },
        undefined,
        { shallow: true, scroll: false },
      );
    } else {
      delete router.query.stilling;
      router.replace(
        {
          query: { ...router.query },
        },
        undefined,
        { shallow: true, scroll: false },
      );
    }
  }, [selectedAccordionIds]);

  if (error) return null;
  if (loading) return <Box>Sæki stillingar</Box>;

  const service = data?.service;
  const serviceType = service?.__typename;

  const COLOR = isAlltSaman ? 'orange' : serviceColorMap(service?.type);
  const settingsCategories: SettingsCategoriesType[] = [
    {
      id: 'general',
      name: t('generalSettings.title'),
      icon: 'settings',
      content: (
        <GeneralSettingsContainer
          subscriptionId={service?.__typename === 'MobileService' ? service?.phoneNumber ?? '' : ''}
          color={COLOR}
        />
      ),
      active: serviceType === 'MobileService',
    },
    {
      id: 'service',
      name: t('service.title'),
      icon: 'novaLogo',
      content: <ServiceSettingsContainer color={COLOR} />,
      active:
        !isAlltSaman &&
        (serviceType === 'MobileService' ||
          serviceType === 'FiberService' ||
          serviceType === 'MobileInternetService'),
    },
    {
      id: 'yourservice',
      name: t('yourService.title'),
      icon: 'userCircle',
      content: <ChangeServiceContainer serviceId={service?.id || ''} />,
      active: serviceType === 'MobileService' || serviceType === 'MobileInternetService',
    },
    {
      id: 'user',
      name: t('userSection.title'),
      icon: 'happy',
      content:
        serviceType === 'FiberService' ? (
          <UserInfoSettingsContainer color={COLOR} />
        ) : (
          <UserSettingsContainer />
        ),
      active: (authentication?.isStaff && serviceType !== 'TvService') || false,
    },
    {
      id: 'payer',
      name: t('payerSettings.title'),
      icon: 'wallet',
      content: <PayersettingsContainer color={COLOR} contractId={contractId} />,
      active: (authentication?.isStaff && serviceType !== 'TvService' && !isAlltSaman) || false,
    },
    {
      id: 'department',
      name: t('departmentSettings.title'),
      icon: 'company',
      content: (
        <DepartmentSettingsContainer
          contractId={contractId}
          color={COLOR}
          isCustomerCompany={isCompanyData?.customer?.isCompany}
        />
      ),
      active:
        (serviceType !== 'TvService' &&
          ((authentication?.isStaff && isPayerCompanyData?.customer?.isCompany === true) ||
            isCompanyData?.customer?.isCompany)) ||
        false,
    },
    {
      id: 'phonenumber',
      name: t('phonenumber.title'),
      icon: 'phone',
      content: <PhonenumberSettingsContainer />,
      active: serviceType === 'MobileService',
    },
    {
      id: 'simcard',
      name: t('simcard.title'),
      icon: 'mobile',
      content: (
        <SimcardSettingsContainer
          subscriptionId={service?.__typename === 'MobileService' ? service?.phoneNumber ?? '' : ''}
          isStaff={authentication?.isStaff}
          color={COLOR}
          userName={service?.__typename === 'MobileService' ? service?.user?.name ?? '' : ''}
          userNationalId={
            service?.__typename === 'MobileService' ? service?.user?.nationalId ?? '' : ''
          }
        />
      ),
      active: serviceType === 'MobileService',
    },
    {
      id: 'abroad',
      name: t('abroadSettings.title'),
      icon: 'tag',
      content: (
        <AbroadSettingsContainer
          subscriptionId={service?.__typename === 'MobileService' ? service?.phoneNumber ?? '' : ''}
          color={COLOR}
        />
      ),
      active: serviceType === 'MobileService',
    },
    {
      id: 'paymentMethod',
      name: t('paymentSettings.title'),
      icon: 'creditcard',
      content: (
        <PaymentMethod
          contractId={contractId?.toString() ?? ''}
          color={COLOR}
          shouldRedirect={false}
        />
      ),
      active: authentication?.isTokenValid || false,
    },
    {
      id: 'move',
      name: t('moveSettings.title'),
      icon: 'location',
      content: (
        <MoveSettingsContainer serviceId={(router.query.serviceId as string) ?? ''} color={COLOR} />
      ),
      active: (isDev && authentication?.isTokenValid && serviceType === 'FiberService') || false,
    },
    {
      id: 'cancelContract',
      name: t('cancelContract.title'),
      icon: 'close',
      content: hasTermination ? (
        <FiberServiceTermination
          termination={terminationsData?.terminations[0]}
          terminationRefetch={terminationRefetch}
          hasPingAlert={false}
        />
      ) : (
        <CancelContractContainer
          isTengir={serviceType === 'FiberService' && service?.provider === FiberProvider.Tengir}
        />
      ),
      active:
        serviceType === 'MobileInternetService' ||
        serviceType === 'MobileService' ||
        serviceType === 'FiberService',
    },
    {
      id: 'changeCeiling',
      name: 'Þak',
      icon: 'creditcardOff',
      content: <ChangeCeilingContainer color={COLOR} contractId={contractId ?? ''} />,
      active:
        (((authentication?.isStaff && isPayerCompanyData?.customer?.isCompany === true) ||
          isCompanyData?.customer?.isCompany) &&
          serviceType === 'FiberService') ||
        false,
    },
    {
      id: 'changeInvoiceDescription',
      name: 'Skýring á reikning',
      icon: 'receipt',
      content: <ChangeInvoiceDescription color={COLOR} contractId={contractId ?? ''} />,
      active:
        (((authentication?.isStaff && isPayerCompanyData?.customer?.isCompany === true) ||
          isCompanyData?.customer?.isCompany) &&
          serviceType === 'FiberService') ||
        false,
    },
  ];

  const handleAddId = (id: string) => {
    if (!selectedAccordionIds?.includes(id)) {
      setSelectedAccordionIds((ids) => (ids?.length ? [...ids, id] : [id]));
    }
  };

  const handleRemoveId = (id: string) => {
    if (selectedAccordionIds?.includes(id)) {
      setSelectedAccordionIds((ids) => ids?.filter((accordionId) => accordionId !== id));
    }
  };

  return (
    <ServiceWrapper>
      {settingsCategories.map(({ id, name, icon, content, active }) => {
        if (active) {
          return (
            <Box key={id} id={id} paddingBottom={4}>
              <SimpleAccordion
                onExpand={() => handleAddId(id)}
                onCollapse={() => handleRemoveId(id)}
                hasBoxShadow
                title={name}
                icon={icon}
                color={COLOR}
                isExpanded={selectedAccordionIds?.includes(id)}
              >
                <Box
                  paddingTop={[3, 5]}
                  paddingBottom={[8]}
                  paddingLeft={[3, 9]}
                  paddingRight={[3, 5]}
                >
                  {content}
                </Box>
              </SimpleAccordion>
            </Box>
          );
        }
      })}
    </ServiceWrapper>
  );
};

Thjonusta.getInitialProps = ({ pathname }: IContext) => {
  return {
    pathname,
    namespacesRequired: ['stillingar', 'errors'],
  };
};

export default inject('authentication')(Thjonusta);
